<?php

namespace app\admin\controller;

use app\models\{Business, PlatClass, PlatSons, AgentArea, Goods, GoodsSpec, RecpeopleLog, Region, BusinessArea, Compent, User as Users, Order, OrderGoods, Recpeople, RecpeopleArea, RecpeopleProject, BussinessLog};
use think\Db;
use think\Validate;

class Shop extends Base
{

    public function compent_add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'specid' => 'require',
                'star' => 'require|in:1,2,3,4,5',
                'text' => 'require',
                'nickName' => 'require',
                'avatarUrl' => 'require',
            ], [
                'specid.require' => '规格ID不能为空',
                'star.require' => '星级不能不能为空',
                'star.in' => '星级类型不正确',
                'nickName.require' => '昵称不能为空',
                'avatarUrl.require' => '头像不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!empty($data['images'])) {
                $data['images'] = json_encode($data['images'], true);
            } else {
                $data['images'] = '';
            }
            $goodmodel = new Goods();
            $specmodel = new GoodsSpec();
            //查找规格信息
            $spec = $specmodel->where(['id' => $data['specid'], 'isdel' => 1])->find();
            if (empty($spec)) {
                return json(['code' => 1, 'data' => [], 'msg' => '规格信息不存在']);
            }
            $data['goodsid'] = $spec['goodid'];
            $data['businessid'] = $spec['businessid'];
            Db::startTrans();
            try {
                (new Compent())->allowfield(true)->save($data);
                Db::commit();
                if ($data['star'] > 3) {
                    $goodmodel->where('id', $spec['goodid'])->Inc(['goodspj' => 1, 'sale' => 1])->update();
                }
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
            }
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $specmodel = new GoodsSpec();
            $goodsid = $this->request->get('goodsid/d', 0);
            $results = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $goodsid])->select();
            return view(null, [
                'row' => $results
            ]);
        }
    }

    public function users()
    {
        $businessid = $this->request->get('business/d', 0);
        $results = (new Users())->alias('u')
            ->where(['o.status' => 4, 'o.businessid' => $businessid])
            ->distinct(true)
            ->join('order o', 'o.user_id= u.id')->field('u.*');
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        return view(null, [
            'list' => $results
        ]);
    }


    public function businesslog()
    {
        $model = new BussinessLog();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['id'])) {
            $results = $results->where('user_id', $data['id']);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        return view(null, [
            'list' => $results
        ]);
    }

    public function peopleproject_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'peoples' => 'require',
                'status' => 'require|in:1,2,3',
                'goodsid' => 'require'
            ], [
                'peoples.require' => '技工不能为空',
                'status.require' => '状态不能为空',
                'status.in' => '状态不正确',
                'goodsid.require' => '服务项目不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['goodsid'] = json_encode($data['goodsid'], true);
            //查询负责区域是否已存在
            $project = (new RecpeopleProject())->where([
                'peoples' => $data['peoples'],
            ])->find();
            if (!empty($project)) {
                $res = (new RecpeopleProject())->allowfield(true)->save($data, ['id' => $project['id']]);
            } else {
                $res = (new RecpeopleProject())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('peopleid/d', 0);
            $business = (new Recpeople())->where('id', $id)->value('business') ?? 0;
            //获取商城下面所有技术项目
            $good = (new Goods())->where(['businessid' => $business, 'type' => 1, 'isdel' => 1])->select();
            $row = (new RecpeopleProject())->where('peoples', $id)->find();
            if ($row) {
                $row['goodsid'] = json_decode($row['goodsid'], true);
            }
            return view('', [
                'business' => $business,
                'row' => $row,
                'id' => $id,
                'good' => $good
            ]);
        }
    }

    public function peoplearea()
    {
        $list = (new RecpeopleArea())->order('id desc');
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('title', 'like', '%' . $data['title'] . '%');
        }
        $province = (new Region())->where(['level' => 1])->select();
        $city = [];
        $area = [];
        $street = [];
        if (!empty($data['province'])) {
            $city_top = (new Region())->where(['level' => 1, 'area_code' => $data['province']])->value('id') ?? 0;
            $city = (new Region())->where(['level' => 2, 'parent_id' => $city_top])->select();
            $list = $list->where(['province' => $data['province']]);
        }
        if (!empty($data['city'])) {
            $area_top = (new Region())->where(['level' => 2, 'area_code' => $data['city']])->value('id') ?? 0;
            $area = (new Region())->where(['level' => 3, 'parent_id' => $area_top])->select();
            $list = $list->where(['city' => $data['city']]);
        }
        if (!empty($data['area'])) {
            $street_top = (new Region())->where(['level' => 3, 'area_code' => $data['area']])->value('id') ?? 0;
            $street = (new Region())->where(['level' => 4, 'parent_id' => $street_top])->select();
            $list = $list->where(['area' => $data['area']]);
        }
        if (!empty($data['street'])) {
            $list = $list->where(['street' => $data['street']]);
        }
        if (!empty($data['peopleid'])) {
            $list = $list->where(['peoples' => $data['peopleid']]);
        }
        if (!empty($data['type'])) {
            $list = $list->where(['type' => $data['type']]);
        }
        $shop = (new Recpeople())->field('id,mobile,name')->select();
        $list = $list->paginate(10)->each(function ($row) {
            $row['province_list'] = [];
            $row['city_list'] = [];
            $row['area_list'] = [];
            $row['people_name'] = (new Recpeople())->where('id', $row['peoples'])->value('mobile');
            $row['street_list'] = [];
            $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->value('name') ?? '';
            $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->value('name') ?? '';
            $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->value('name') ?? '';
            $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->value('name') ?? '';
            return $row;
        });
        return view(null, [
            'list' => $list,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'street' => $street,
            'shop' => $shop
        ]);
    }

    public function peoplearea_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'peoples' => 'require',
                'type' => 'require|in:1,2',
                'province' => 'require',
                'city' => 'require',
                'area' => 'require',
                'street' => 'require|gt:0',
            ], [
                'peoples.require' => '技工不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确',
                'province.require' => '省份不能为空',
                'city.require' => '城市不能为空',
                'area.require' => '区域不能为空',
                'street.require' => '街道不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            //查询负责区域是否已存在
            $businessarea = (new RecpeopleArea())->where([
                'type' => $data['type'],
                'province' => $data['province'],
                'city' => $data['city'],
                'area' => $data['area'],
                'street' => $data['street'],
                'peoples' => $data['peoples'],
            ])->find();
            if (!empty($data['id'])) {
                if (!empty($businessarea) && $data['id'] != $businessarea['id']) {
                    return json(['status' => 1, 'msg' => '该类型区域已存在']);
                }
                $res = (new RecpeopleArea())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($businessarea)) {
                    return json(['status' => 1, 'msg' => '该类型区域已存在']);
                }
                $res = (new RecpeopleArea())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new RecpeopleArea())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            $shop = (new Recpeople())->field('id,mobile,name')->select();
            if (!empty($row)) {
                $parent = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->find();
                $city = (new Region())->where(['level' => 2, 'parent_id' => $parent['id']])->select();
                $carent = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->find();
                $area = (new Region())->where(['level' => 3, 'parent_id' => $carent['id']])->select();
                $aarent = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->find();
                $street = (new Region())->where(['level' => 4, 'parent_id' => $aarent['id']])->select();
            } else {
                $peoples = $this->request->get('peopleid/d', 0);
                if (!empty($peoples)) {
                    $row['peoples'] = $peoples;
                }
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'shop' => $shop

            ]);
        }
    }


    public function peoplearea_del()
    {
        $id = trim(input('id'), ',');
        $model = new RecpeopleArea();
        $res = $model->where(['id' => $id])->delete();
        if ($res) {
            return json(['code' => 0, 'status' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'status' => 0, 'data' => [], 'msg' => '操作失败，请重试']);
    }

    public function people()
    {
        $model = new Recpeople();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('mobile', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['status'])) {
            $results = $results->where('status', $data['status']);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            if ($result['business'] > 0) {
                $result['business_name'] = (new Business())->where('id', $result['business'])->value('title');
            } else {
                $result['business_name'] = '未绑定商家';
            }
        }
        return view(null, [
            'list' => $results
        ]);
    }

    public function people_buiness()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'value' => 'require'
            ], [
                'id.require' => '技工ID不能为空',
                'value.require' => '商家账号不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $people = (new Recpeople())->where('id', $data['id'])->find();
            if (empty($people)) {
                return json(['code' => 1, 'data' => [], 'msg' => '技工账号不存在']);
            }
            //判断商家是否存在
            $business = (new Business())->where(['account' => $data['value']])->find();
            if (empty($business)) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家不存在']);
            }
            if ($people['business'] == $business['id']) {
                return json(['code' => 1, 'data' => [], 'msg' => '绑定商家未进行更改']);
            }
            Db::startTrans();
            try {
                (new Recpeople())->where(['id' => $people['id']])->update(['business' => $business['id']]);
                (new RecpeopleArea())->where(['peoples' => $people['id']])->delete();
                (new RecpeopleProject())->where(['peoples' => $people['id']])->delete();
                (new RecpeopleLog())->where(['status' => 1, 'peopleid' => $people['id']])->update(['status' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
                return json(['code' => 1, 'status' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
            }
            return json(['code' => 0, 'status' => 0, 'data' => [], 'msg' => '操作成功']);
        }
    }


    public function people_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'status' => 'require',
            ], [
                'name.require' => '技工名称不能为空',
                'mobile.require' => '账号不能为空',
                'status.require' => '状态不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Recpeople();
            //查找店铺名称、账号是否已经被使用
            $haveshop = $model->where('mobile', $data['mobile'])->find();
            if (!empty($data['id'])) {
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Recpeople();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }

    public function shoplist()
    {
        $model = new Business();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('title|account', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['status'])) {
            $results = $results->where('status', $data['status']);
        }
        if (!empty($data['agentid'])) {
            //查询管理区域
            $results = $results->where(['agentid' => $data['agentid']]);
        }
        //查询代理ID
        if (!empty($data['agent'])) {
            //查询管理区域
            $citys = [];
            $areas = [];
            $streets = [];
            $agentarea = (new AgentArea())->where(['agentid' => $data['agent']])->select();
            foreach ($agentarea as $agareas) {
                if ($agareas['type'] == 2) {
                    $citys[] = $agareas['city'];
                }
                if ($agareas['type'] == 3) {
                    $areas[] = $agareas['area'];
                }
                if ($agareas['type'] == 4) {
                    $streets[] = $agareas['street'];
                }
            }
            $where = [
                'city' => $citys,
                'type' => [2, 3, 4]
            ];
            $where1 = [
                'area' => $areas,
                'type' => [3, 4]
            ];
            $where2 = [
                'street' => $streets,
                'type' => [4]
            ];
            $businessid = (new BusinessArea())->whereOr(function ($query) use ($where) {
                $query->where($where);
            })->whereOr(function ($query) use ($where1) {
                $query->where($where1);
            })->whereOr(function ($query) use ($where2) {
                $query->where($where2);
            })->group('businessid')->column('businessid') ?? [];
            $results = $results->where(['id' => $businessid]);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            $result['income'] = (new BussinessLog())->where(['user_id' => $result['id'], 'type' => 1])->sum('money') ?? 0;
            $result['area'] = (new BusinessArea())->where(['businessid' => $result['id']])->count();
            $result['goods'] = (new Goods())->where(['businessid' => $result['id'], 'isSale' => 1, 'isdel' => 1])->count();
        }
        return view(null, [
            'list' => $results
        ]);
    }

    public function shoplist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'remark' => 'require',
                'account' => 'require',
                'status' => 'require',
                'fwtime' => 'require'
            ], [
                'title.require' => '商家名称不能为空',
                'remark.require' => '商家备注不能为空',
                'account.require' => '商家备注不能为空',
                'status.require' => '商家状态不能为空',
                'fwtime.require' => '服务时间不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $fwtime = explode('-', $data['fwtime']);
            if (count($fwtime) != 2) {
                return json(['code' => 1, 'data' => [], 'msg' => '时间格式错误']);
            }
            if (strtotime($fwtime[0]) > strtotime($fwtime[1])) {
                return json(['code' => 1, 'data' => [], 'msg' => '时间范围错误']);
            }
            if (abs(strtotime($fwtime[0]) - strtotime($fwtime[1])) < 3600) {
                return json(['code' => 1, 'data' => [], 'msg' => '时间间隔不能低于一个小时']);
            }

            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Business();
            //查找店铺名称、账号是否已经被使用
            $isshop = $model->where('title', $data['title'])->find();
            $haveshop = $model->where('account', $data['account'])->find();
            if (!empty($data['id'])) {
                if (!empty($isshop) && $isshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '店铺名已被使用']);
                }
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '店铺账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
                if ($res) {
                    return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
                }
                return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
            } else {
                if (!empty($isshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '店铺名已被使用']);
                }
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '店铺账号已被使用']);
                }
                switch ($data['type']) {
                    case '1':
                        $data['province'] = $data['province'] ?? 0;
                        $data['city'] = $data['city'] ?? 0;
                        $data['area'] = $data['area'] ?? 0;
                        $data['street'] = $data['street'] ?? 0;
                        return json(['status' => 1, 'msg' => '无权限']);
                        break;
                    case '2':
                        if (empty($data['province'])) {
                            return json(['status' => 1, 'msg' => '请选择省份']);
                        }
                        if (empty($data['city'])) {
                            return json(['status' => 1, 'msg' => '请选择城市']);
                        }
                        $data['area'] = 0;
                        $data['street'] = 0;
                        break;
                    case '3':
                        if (empty($data['province'])) {
                            return json(['status' => 1, 'msg' => '请选择省份']);
                        }
                        if (empty($data['city'])) {
                            return json(['status' => 1, 'msg' => '请选择城市']);
                        }
                        if (empty($data['area'])) {
                            return json(['status' => 1, 'msg' => '请选择区域']);
                        }
                        $data['street'] = 0;
                        break;
                    case '4':
                        if (empty($data['province'])) {
                            return json(['status' => 1, 'msg' => '请选择省份']);
                        }
                        if (empty($data['city'])) {
                            return json(['status' => 1, 'msg' => '请选择城市']);
                        }
                        if (empty($data['area'])) {
                            return json(['status' => 1, 'msg' => '请选择区域']);
                        }
                        if (empty($data['street'])) {
                            return json(['status' => 1, 'msg' => '请选择街道']);
                        }
                        break;
                    default:
                        return json(['status' => 1, 'msg' => '管理员类型错误']);
                        break;
                }
                Db::startTrans();
                try {
                    $id = $model->strict(false)->insertGetId($data);
                    $data['businessid'] = $id;
                    $res = (new BusinessArea())->allowfield(true)->save($data);
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
                return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
            }
        } else {
            $model = new Business();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street
            ]);
        }
    }

    public function compent()
    {
        $model = new Compent();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['id'])) {
            $results = $results->where('goodsid', $data['id']);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            $result['images'] = json_decode($result['images'], true);
            if (!empty($result['nickName'])) {
                $user['nickName'] = $result['nickName'];
                $user['avatarUrl'] = $result['avatarUrl'];
                $result['user'] = $user;
            } else {
                $result['user'] = (new Users())->field('nickName,avatarUrl')->where('id', $result['user_id'])->find();
            }
            $result['spec_name'] = (new GoodsSpec())->where('id', $result['specid'])->value('name');
        }
        return view(null, [
            'list' => $results
        ]);
    }

    public function goodslist()
    {
        $model = new Goods();
        $shopmodel = new Business();
        $data = $this->request->get();
        $results = $model->where('isdel', 1)->order('id desc');
        $province = (new Region())->where(['level' => 1])->select();
        $city = [];
        $area = [];
        $street = [];
        $ptsons = [];
        if (!empty($data['title'])) {
            $results = $results->where('title', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['platclassid'])) {
            $ptsons = (new PlatSons())->where('isshow', 1)->where('platclassid', $data['platclassid'])->order(['sort' => 'desc', 'id' => 'desc'])->select();
            $results = $results->where('classid', $data['platclassid']);
        }
        if (!empty($data['type'])) {
            $results = $results->where('type', $data['type']);
        }
        if (!empty($data['sonsid'])) {
            $results = $results->where('sonsid', $data['sonsid']);
        }
        if (!empty($data['businessid'])) {
            $results = $results->where('businessid', $data['businessid']);
        }
        $where = [];
        $where1 = [];
        $where2 = [];
        $where3 = [];
        if (!empty($data['province'])) {
            $city_top = (new Region())->where(['level' => 1, 'area_code' => $data['province']])->value('id') ?? 0;
            $city = (new Region())->where(['level' => 2, 'parent_id' => $city_top])->select();
            $where = [
                'type' => 1
            ];
        }
        if (!empty($data['city'])) {
            $area_top = (new Region())->where(['level' => 2, 'area_code' => $data['city']])->value('id') ?? 0;
            $area = (new Region())->where(['level' => 3, 'parent_id' => $area_top])->select();
            $where1 = [
                'type' => 2,
                'city' => $data['city'] ?? 0
            ];
        }
        if (!empty($data['area'])) {
            $street_top = (new Region())->where(['level' => 3, 'area_code' => $data['area']])->value('id') ?? 0;
            $street = (new Region())->where(['level' => 4, 'parent_id' => $street_top])->select();
            $where2 = [
                'type' => 3,
                'area' => $data['area'] ?? 0
            ];
        }
        if (!empty($data['street'])) {
            $where3 = [
                'type' => 4,
                'street' => $data['street'] ?? 0
            ];
        }
        if (!empty($where) || !empty($where1) || !empty($where2) || !empty($where3)) {
            $businessid = (new BusinessArea())->whereOr(function ($query) use ($where) {
                $query->where($where);
            })->whereOr(function ($query) use ($where1) {
                $query->where($where1);
            })->whereOr(function ($query) use ($where2) {
                $query->where($where2);
            })->whereOr(function ($query) use ($where3) {
                $query->where($where3);
            })->column('businessid');
            $results = $results->where(['businessid' => $businessid]);
        }
        $results = $results->where(['type' => [1, 2]])->paginate(10, false, ['query' => $this->request->param()]);
        $shop = (new Business())->field('id,title,account')->where('status', 1)->select();
        $platclass = (new PlatClass())->where('isshow', 1)->where('type', 1)->order(['sort' => 'desc', 'id' => 'desc'])->select();
        foreach ($results as $result) {
            $result['images'] = json_decode($result['images'], true) ?? [];
            $result['shopname'] = $shopmodel->where('id', $result['businessid'])->value('title');
            $result['class_name'] = (new PlatClass())->where('id', $result['classid'])->value('name');
            $result['sons_name'] = (new PlatSons())->where('id', $result['sonsid'])->value('name');
            $result['goodspec'] = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $result['id']])->order('is_default desc')->find();
        }
        return view(null, [
            'list' => $results,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'street' => $street,
            'shop' => $shop,
            'platclass' => $platclass,
            'ptsons' => $ptsons,
        ]);
    }


    public function goodslist2()
    {
        $model = new Goods();
        $shopmodel = new Business();
        $data = $this->request->get();
        $results = $model->where('isdel', 1)->order('id desc');
        $province = (new Region())->where(['level' => 1])->select();
        $city = [];
        $area = [];
        $street = [];
        $ptsons = [];
        if (!empty($data['title'])) {
            $results = $results->where('title', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['platclassid'])) {
            $ptsons = (new PlatSons())->where('isshow', 1)->where('platclassid', $data['platclassid'])->order(['sort' => 'desc', 'id' => 'desc'])->select();
            $results = $results->where('classid', $data['platclassid']);
        }
        if (!empty($data['sonsid'])) {
            $results = $results->where('sonsid', $data['sonsid']);
        }
        if (!empty($data['businessid'])) {
            $results = $results->where('businessid', $data['businessid']);
        }
        if (!empty($data['type'])) {
            $results = $results->where('type', $data['type']);
        }
        if (!empty($data['recomm'])) {
            $results = $results->where('recomm', $data['recomm']);
        }
        $results = $results->where(['type' => [3, 4]])->paginate(10, false, ['query' => $this->request->param()]);
        $shop = (new Business())->field('id,title,account')->where('status', 1)->select();
        $platclass = (new PlatClass())->where('isshow', 1)->where('type', 2)->order(['sort' => 'desc', 'id' => 'desc'])->select();
        foreach ($results as $result) {
            $result['images'] = json_decode($result['images'], true) ?? [];
            $result['shopname'] = $shopmodel->where('id', $result['businessid'])->value('title');
            $result['class_name'] = (new PlatClass())->where('id', $result['classid'])->value('name');
            $result['sons_name'] = (new PlatSons())->where('id', $result['sonsid'])->value('name');
            $result['goodspec'] = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $result['id']])->order('is_default desc')->find();
        }
        return view(null, [
            'list' => $results,
            'shop' => $shop,
            'platclass' => $platclass,
            'ptsons' => $ptsons,
        ]);
    }

    public function goodslist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'type' => 'require|in:1,2',
                'businessid' => 'require',
                'descs' => 'require',
                'images' => 'require',
                'classid' => 'require',
                'sonsid' => 'require',
                'spec' => 'require'
            ], [
                'title.require' => '服务名称不能为空',
                'type.require' => '服务类型不能为空',
                'type.in' => '服务类型不正确',
                'businessid.require' => '商家ID不能为空',
                'descs.require' => '服务描述不能为空',
                'images.require' => '图片不能为空',
                'classid.require' => '平台大类不能为空',
                'sonsid.require' => '平台分类不能为空',
                'spec.require' => '规格必须填写'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!empty($data['images'])) {
                $data['images'] = json_encode($data['images'], true);
            }
            if (!empty($data['parpam'])) {
                $data['parpam'] = json_encode($data['parpam'], true);
            }
            if (empty($data['spec']) || count($data['spec']) <= 0) {
                return json(['code' => 1, 'data' => [], 'msg' => '规格信息不能少于一个']);
            }
            if (isset($data['file'])) {
                unset($data['file']);
            }
            $shopmodel = new Business();
            $goodmodel = new Goods();
            $platsonsmodel = new PlatSons();
            $specmodel = new GoodsSpec();
            //查找商家是否存
            $shoplist = $shopmodel->where('id', $data['businessid'])->find();
            if (!$shoplist) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家不存在']);
            }
            //查找分类是否存在
            $platsons = $platsonsmodel->where(['id' => $data['sonsid']])->find();
            if (empty($platsons)) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家分类不存在']);
            }
            $data['classid'] = $platsons['platclassid'];
            $insert = $data;
            unset($insert['spec']);
            if (empty($data['id'])) {
                Db::startTrans();
                try {
                    $data['id'] = $goodmodel->insertGetid($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['businessid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            } else {
                Db::startTrans();
                try {
                    $goodmodel->where('id', $data['id'])->update($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['businessid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            }
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $model = new Goods();
            $specmodel = new GoodsSpec();
            $shopmodel = new Business();
            $cate = [];
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            $platsons = [];
            $shoplist = $shopmodel->field('id,title,account')->select();
            if ($results) {
                $results['images'] = json_decode($results['images'], true) ?? [];
                $results['parpam'] = json_decode($results['parpam'], true) ?? [];
                $results['speclist'] = $specmodel->order('is_default desc')->where(['businessid' => $results['businessid'], 'isdel' => 1, 'goodid' => $results['id']])->select();
                $platsons = (new PlatSons())->where('platclassid', $results['classid'])->where('isshow', 1)->select();
            } else {
                $results['businessid'] = $this->request->get('businessid/d', 0);
            }

            $platclass = (new PlatClass())->where('isshow', 1)->select();
            return view(null, [
                'row' => $results,
                'shoplist' => $shoplist,
                'platclass' => $platclass,
                'platsons' => $platsons
            ]);
        }
    }

    public function goodslist_edit2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'type' => 'require|in:3,4',
                'businessid' => 'require',
                'descs' => 'require',
                'images' => 'require',
                'spec' => 'require'
            ], [
                'title.require' => '服务名称不能为空',
                'type.require' => '服务类型不能为空',
                'type.in' => '服务类型不正确',
                'businessid.require' => '商家ID不能为空',
                'descs.require' => '服务描述不能为空',
                'images.require' => '图片不能为空',
                'spec.require' => '规格必须填写'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!empty($data['images'])) {
                $data['images'] = json_encode($data['images'], true);
            }
            if (!empty($data['parpam'])) {
                $data['parpam'] = json_encode($data['parpam'], true);
            }
            if (empty($data['spec']) || count($data['spec']) <= 0) {
                return json(['code' => 1, 'data' => [], 'msg' => '规格信息不能少于一个']);
            }
            if (isset($data['file'])) {
                unset($data['file']);
            }
            if ($data['type'] == 4) {
                $data['classid'] = 0;
            } else {
                if (empty($data['classid'])) {
                    return json(['code' => 1, 'data' => [], 'msg' => '分类选项不能为空']);
                }
            }
            $shopmodel = new Business();
            $goodmodel = new Goods();
            $platsonsmodel = new PlatSons();
            $specmodel = new GoodsSpec();
            //查找商家是否存
            $shoplist = $shopmodel->where('id', $data['businessid'])->find();
            if (!$shoplist) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家不存在']);
            }
            //查找分类是否存在
            if (!empty($data['sonsid'])) {
                $platsons = $platsonsmodel->where(['id' => $data['sonsid']])->find();
                if (empty($platsons)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '分类不存在']);
                }
            } else {
                $data['sonsid'] = 0;
            }
            $data['classid'] = $platsons['platclassid'] ?? $data['classid'];
            $insert = $data;
            unset($insert['spec']);
            if (empty($data['id'])) {
                Db::startTrans();
                try {
                    $data['id'] = $goodmodel->insertGetid($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['businessid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            } else {
                Db::startTrans();
                try {
                    $goodmodel->where('id', $data['id'])->update($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['businessid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            }
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $model = new Goods();
            $specmodel = new GoodsSpec();
            $shopmodel = new Business();
            $cate = [];
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            $platsons = [];
            $shoplist = $shopmodel->field('id,title,account')->select();
            if ($results) {
                $results['images'] = json_decode($results['images'], true) ?? [];
                $results['parpam'] = json_decode($results['parpam'], true) ?? [];
                $results['speclist'] = $specmodel->order('is_default desc')->where(['businessid' => $results['businessid'], 'isdel' => 1, 'goodid' => $results['id']])->select();
                $platsons = (new PlatSons())->where('platclassid', $results['classid'])->where('isshow', 1)->select();
            }
            $platclass = (new PlatClass())->where('isshow', 1)->where('type', 2)->select();
            return view(null, [
                'row' => $results,
                'shoplist' => $shoplist,
                'platclass' => $platclass,
                'platsons' => $platsons
            ]);
        }
    }

    public function goodslist_del()
    {
        $id = trim(input('id'), ',');
        $model = new Goods();
        $res = $model->where(['id' => $id])->update(['isdel' => 2]);
        if ($res) {
            return json(['code' => 0, 'status' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
    }

    public function goodsspec_del()
    {
        $id = trim(input('id'), ',');
        $model = new GoodsSpec();
        $goodsspec = $model->where(['id' => $id, 'isdel' => 1])->find();
        if (empty($goodsspec)) {
            return json(['code' => 1, 'data' => [], 'msg' => '库存规格不存在']);
        }
        //查询规格商品是否超过1个
        $havespec = $model->where(['goodid' => $goodsspec['goodid'], 'isdel' => 1])->count();
        if ($havespec <= 1) {
            return json(['code' => 1, 'data' => [], 'msg' => '库存规格必须保留一个']);
        }
        $res = $model->where(['id' => $id])->update(['isdel' => 2]);
        if ($res) {
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
    }

    public function shoparea()
    {
        $list = (new BusinessArea())->order('id desc');
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('title', 'like', '%' . $data['title'] . '%');
        }
        $province = (new Region())->where(['level' => 1])->select();
        $city = [];
        $area = [];
        $street = [];
        if (!empty($data['businessid'])) {
            $list = $list->where(['businessid' => $data['businessid']]);
        }
        if (!empty($data['province'])) {
            $city_top = (new Region())->where(['level' => 1, 'area_code' => $data['province']])->value('id') ?? 0;
            $city = (new Region())->where(['level' => 2, 'parent_id' => $city_top])->select();
            $list = $list->where(['province' => $data['province']]);
        }
        if (!empty($data['city'])) {
            $area_top = (new Region())->where(['level' => 2, 'area_code' => $data['city']])->value('id') ?? 0;
            $area = (new Region())->where(['level' => 3, 'parent_id' => $area_top])->select();
            $list = $list->where(['city' => $data['city']]);
        }
        if (!empty($data['area'])) {
            $street_top = (new Region())->where(['level' => 3, 'area_code' => $data['area']])->value('id') ?? 0;
            $street = (new Region())->where(['level' => 4, 'parent_id' => $street_top])->select();
            $list = $list->where(['area' => $data['area']]);
        }
        if (!empty($data['street'])) {
            $list = $list->where(['street' => $data['street']]);
        }
        $list = $list->paginate(10)->each(function ($row) {
            $row['province_list'] = [];
            $row['city_list'] = [];
            $row['area_list'] = [];
            $row['street_list'] = [];
            $row['business_name'] = (new Business())->where(['id' => $row['businessid']])->value('title') ?? '';
            $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->value('name') ?? '';
            $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->value('name') ?? '';
            $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->value('name') ?? '';
            $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->value('name') ?? '';
            return $row;
        });
        $shop = (new Business())->field('id,title,account')->where('status', 1)->select();
        return view(null, [
            'list' => $list,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'street' => $street,
            'shop' => $shop
        ]);
    }

    public function shoparea_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'businessid' => 'require',
                'type' => 'require|in:1,2,3,4'
            ], [
                'businessid.require' => '服务商家不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确'
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            //查询有没有添加下级区域 需要删掉下级区域
            $havearea = (new BusinessArea())->where(['businessid' => $data['businessid'], 'type' => 1])->find();
            if (!empty($havearea)) {
                return json(['status' => 1, 'msg' => '您已添加最高级别区域权限，无需重复添加']);
            }
            switch ($data['type']) {
                case '1':
                    $data['province'] = $data['province'] ?? 0;
                    $data['city'] = $data['city'] ?? 0;
                    $data['area'] = $data['area'] ?? 0;
                    $data['street'] = $data['street'] ?? 0;
                    break;
                case '2':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    //添加高级别需要删除低级别权限
                    $havearea = (new BusinessArea())->where(['businessid' => $data['businessid'], 'type' => [3, 4], 'city' => $data['city']])->find();
                    if (!empty($havearea)) {
                        return json(['status' => 1, 'msg' => '添加或更改更高级别区域管理前请先确认并删除低级别区域管理权限']);
                    }
                    $data['area'] = 0;
                    $data['street'] = 0;
                    break;
                case '3':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new BusinessArea())->where(['businessid' => $data['businessid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['status' => 1, 'msg' => '您已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加高级别需要删除低级别权限
                    $havearea = (new BusinessArea())->where(['businessid' => $data['businessid'], 'type' => 4, 'area' => $data['area']])->find();
                    if (!empty($havearea)) {
                        return json(['status' => 1, 'msg' => '添加或更改更高级别区域管理前请先确认并删除低级别区域管理权限']);
                    }
                    $data['street'] = 0;
                    break;
                case '4':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['status' => 1, 'msg' => '请选择街道']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new BusinessArea())->where(['businessid' => $data['businessid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['status' => 1, 'msg' => '您已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat2 = (new BusinessArea())->where(['businessid' => $data['businessid'], 'type' => 3, 'area' => $data['area']])->find();
                    if (!empty($haveareat2)) {
                        return json(['status' => 1, 'msg' => '您已拥有高级别的区域管理，无需再添加低级别区域管理']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'msg' => '管理员类型错误']);
                    break;
            }
            //查询负责区域是否已存在
            $businessarea = (new BusinessArea())->where([
                'businessid' => $data['businessid'],
                'province' => $data['province'],
                'city' => $data['city'],
                'area' => $data['area'],
                'street' => $data['street']
            ])->find();
            if (!empty($data['id'])) {
                if (!empty($businessarea) && $data['id'] != $businessarea['id']) {
                    return json(['status' => 1, 'msg' => '管理区域已添加，请选择编辑']);
                }
                $res = (new BusinessArea())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($businessarea)) {
                    return json(['status' => 1, 'msg' => '管理区域已添加']);
                }
                $res = (new BusinessArea())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new BusinessArea())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            $shop = (new Business())->field('id,title,account')->where('status', 1)->select();
            if (!empty($row)) {
                $parent = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->find();
                $city = (new Region())->where(['level' => 2, 'parent_id' => $parent['id']])->select();
                $carent = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->find();
                $area = (new Region())->where(['level' => 3, 'parent_id' => $carent['id']])->select();
                $aarent = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->find();
                $street = (new Region())->where(['level' => 4, 'parent_id' => $aarent['id']])->select();
            } else {
                $businessid = $this->request->get('businessid/d', 0);
                if (!empty($businessid)) {
                    $row['businessid'] = $businessid;
                }
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'shop' => $shop
            ]);
        }
    }


    public function shoparea_del()
    {
        $id = trim(input('id'), ',');
        $model = new BusinessArea();
        $res = $model->where(['id' => $id])->delete();
        if ($res) {
            return json(['code' => 0, 'status' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'status' => 0, 'data' => [], 'msg' => '操作失败，请重试']);
    }
}
